import {setStore, getStore, removeStore} from '/src/utils/store.js'
import website from '/src/config/website.js'
import {defineStore} from "pinia";
import {diff} from "../../utils/util.js";
import {ref} from "vue"

const tagObj = {
  label: '', //标题名称
  value: '', //标题的路径
  params: '', //标题的路径参数
  query: '', //标题的参数
  meta: {},//额外参数
  group: [], //分组
}
const isFirstPage = website.isFirstPage;
//tagWel是首页，可以这么理解，tag-welcome
const firstPage = website.fistPage;

//处理首个标签
function setFistTag(list) {
  if (list.length == 1) {
    list[0].close = false;
  } else {
    list.forEach(ele => {
      if (ele.value === firstPage.value && isFirstPage === false) {
        ele.close = false
      } else {
        ele.close = true
      }
    })
  }
}

export const useNavsStore = defineStore('navs', () => {
  //tag的列表
  const tagList = ref(getStore({name: 'tagList'}) || [])
  //当前的tag
  const tag = ref(getStore({name: 'tag'}) || tagObj)
  //tag的第一个页面
  const tagWel = ref(firstPage)


  const tagsKeep = computed(() => {
    return tagList.value.filter(ele => {
      return (ele.meta || {}).keepAlive
    }).map(ele => ele.fullPath)
  })

  // 添加Tag
  function ADD_TAG(newTag) {
    //这一步应该永远执行不到
    if (typeof newTag.name == 'function') newTag.name = newTag.name(newTag.query)
    //step1 处理tag
    tag.value = newTag;
    setStore({name: 'tag', content: this.tag, type: 'session'})
    //step2 处理taglist
    // 如果已经添加了该tag，就不添加了
    // vue2版本中，这里使用了diff函数对比，这里只使用了fullpath对比，应该可以提高速度
    // ele => diff(ele, action))
    // if (this.tagList.some(ele => ele.fullPath == tag.fullPath)) {
    if (tagList.value.some(ele => diff(ele, newTag))) {
      return
    }
    tagList.value.push(newTag)
    // 保存tagList
    setFistTag(tagList.value);
    setStore({name: 'tagList', content: tagList.value, type: 'session'})
  }

  // 删除Tag
  function DEL_TAG(tag) {
    //step1 从原来的taglist中过滤掉入参的tag
    tagList.value = tagList.value.filter(item => {
      // return item.fullPath !== action.fullPath
      return !diff(item, tag);
    })
    // 保存tagList
    setFistTag(tagList.value);
    setStore({name: 'tagList', content: tagList.value, type: 'session'})

  }

  //删除所有tag
  function DEL_ALL_TAG(newTagList = []) {
    //step1 处理tagList
    tagList.value = [tagWel.value]
    setStore({name: 'tagList', content: tagList.value, type: 'session'})
    //step2 设置当前tag为空白
    tag.value = tagObj;
    // 从缓存中删除当前的tag
    removeStore({name: 'tag', type: 'session'});
  }

  //删除其他tag
  function DEL_TAG_OTHER() {
    //step1 处理taglist
    // 出去当前tag和首页，其他的都删除
    tagList.value = tagList.value.filter(item => {
      return [tag.value.value, website.fistPage.value].includes(item.value)
    })
    // 保存tagList
    setFistTag(tagList.value);
    setStore({name: 'tagList', content: tagList.value, type: 'session'})

  }

  return {
    tagList, tag, tagWel,
    tagsKeep,
    ADD_TAG, DEL_TAG, DEL_ALL_TAG, DEL_TAG_OTHER,
  }
})